package com.qzsoft.system.modules.permission.rolebusiness.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qzsoft.jeemis.common.constant.Constant;
import com.qzsoft.jeemis.common.exception.RenException;
import com.qzsoft.jeemis.common.service.BaseService;
import com.qzsoft.jeemis.common.utils.ConvertDictUtils;
import com.qzsoft.jeemis.common.utils.ConvertUtils;
import com.qzsoft.jeemis.common.utils.ExcelUtils;
import com.qzsoft.jeemis.common.utils.TreeUtils;
import com.qzsoft.system.modules.permission.dept.dto.SysDeptDTO;
import com.qzsoft.system.modules.permission.rolebusiness.dao.SysRoleBusinessMapper;
import com.qzsoft.system.modules.permission.rolebusiness.dto.SysRoleBusinessDTO;
import com.qzsoft.system.modules.permission.rolebusiness.dto.SysUserRoleBusinessDTO;
import com.qzsoft.system.modules.permission.rolebusiness.entity.SysRoleBusinessEntity;
import com.qzsoft.system.modules.permission.rolebusiness.service.SysRoleBusinessService;

import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


/**
 * 角色管理(SysRoleBusiness)表服务实现类
 *
 * @author sdmq
 * @since 2020-09-01 13:54:54
 */
@Service("sysRoleBusinessService")
public class SysRoleBusinessServiceImpl extends BaseService implements SysRoleBusinessService {
	private final SqlSession sqlSession;
	@Autowired
	private SysRoleBusinessMapper sysRoleBusinessMapper;

	public SysRoleBusinessServiceImpl(SqlSession sqlSession) {
		this.sqlSession = sqlSession;
	}


	@Override
	public List<SysRoleBusinessDTO> treeFolder() {
		QueryWrapper<SysRoleBusinessEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("has_group", 1).orderByAsc("order_id");
		List<SysRoleBusinessEntity> roleBusinessEntityList = sysRoleBusinessMapper.selectList(queryWrapper);
		List<SysRoleBusinessDTO> roleBusinessGroupDTOList = ConvertUtils
				.sourceToTarget(roleBusinessEntityList, SysRoleBusinessDTO.class);
		roleBusinessGroupDTOList = TreeUtils.build(roleBusinessGroupDTOList, '0');
		return roleBusinessGroupDTOList;
	}

	@Override
	public List<SysRoleBusinessEntity> listRole(String pid) {
		return null;
	}

	/**
	 * SysRoleBusiness数据分页
	 * @param params
	 * @return IPage
	 */
	@Override
	public IPage<SysRoleBusinessEntity> page(Map<String, Object> params) {
		IPage<SysRoleBusinessEntity> page = this
				.getPage(params, Constant.CREATE_DATE, false, SysRoleBusinessEntity.class);
		QueryWrapper<SysRoleBusinessEntity> queryWrapper = this.getQueryWrapper(params, SysRoleBusinessEntity.class);
		IPage<SysRoleBusinessEntity> pageData = sysRoleBusinessMapper.selectPage(page, queryWrapper);
		pageData = ConvertDictUtils.formatDicDataPage(pageData);
		return pageData;
	}

	/**
	 * SysRoleBusiness数据列表
	 * @param params
	 * @return
	 */
	@Override
	public List<SysRoleBusinessEntity> list(Map<String, Object> params) {
		QueryWrapper<SysRoleBusinessEntity> queryWrapper = this.getQueryWrapper(params, SysRoleBusinessEntity.class);
		queryWrapper.eq("has_group", 0);
		List<SysRoleBusinessEntity> entityList = sysRoleBusinessMapper.selectList(queryWrapper);
		entityList = ConvertDictUtils.formatDicDataList(entityList);
		return entityList;
	}

	@Override
	public SysRoleBusinessEntity get(String id) {
		SysRoleBusinessEntity entity = sysRoleBusinessMapper.selectById(id);
		// 如无需代码翻译请屏蔽这句话 提高速度
		entity = ConvertDictUtils.formatDicData(entity);
		return entity;
	}

	/**
	 * SysRoleBusiness保存
	 * createDate creator
	 * updateDate updater 
	 * 字段会自动注入值 如不需要注入请修改SysRoleBusinessEntity
	 * @param entity
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void save(SysRoleBusinessEntity entity) {
		// 检查角色不能重名
		QueryWrapper<SysRoleBusinessEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("has_group", 0).eq("name", entity.getName());
		if (sysRoleBusinessMapper.selectCount(queryWrapper) > 0) {
			throw (new RenException("角色名已经存在"));
		}
		// 检查编码是否存在
		queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("code", entity.getCode());
		if (sysRoleBusinessMapper.selectCount(queryWrapper) > 0) {
			throw (new RenException("编码已经存在"));
		}
		sysRoleBusinessMapper.insert(entity);
	}

	@Override
	public String saveGroup(SysRoleBusinessEntity entity) {
		// 检查同级目录下不能重名
		QueryWrapper<SysRoleBusinessEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("has_group", 1).eq("pid", entity.getPid()).eq("name", entity.getName());
		if (sysRoleBusinessMapper.selectCount(queryWrapper) > 0) {
			throw (new RenException("分组已经存在"));
		}
		// 检查编码是否存在
		queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("code", entity.getCode());
		if (sysRoleBusinessMapper.selectCount(queryWrapper) > 0) {
			throw (new RenException("编码已经存在"));
		}
		entity.setHasGroup(true);
		entity.setHasSystem(false);
		sysRoleBusinessMapper.insert(entity);
		return entity.getId();
	}


	@Override
	@Transactional(rollbackFor = Exception.class)
	public void update(SysRoleBusinessEntity entity) {
		sysRoleBusinessMapper.updateById(entity);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delete(String[] ids) {
		List<String> idArray = new ArrayList<>(ids.length);
		idArray.addAll(Arrays.asList(ids));
		sysRoleBusinessMapper.deleteBatchIds(idArray);
	}

	@Override
	public void exportXls(Map<String, Object> params, HttpServletResponse response) {
		List<SysRoleBusinessEntity> list = this.list(params);
		ExcelUtils.exportExcelToTarget(response, "角色管理导出列表", list, SysRoleBusinessEntity.class);
	}

	/**
	 * 获取所有的业务树
	 *
	 * @return
	 */
	@Override
	public List<SysRoleBusinessDTO> getSysRoleBusiness() {
		List<SysRoleBusinessDTO> rootTreeLists = new ArrayList<>();
		QueryWrapper<SysRoleBusinessEntity> sysRoleBusinessEntityQueryWrapper = new QueryWrapper<>();
		sysRoleBusinessEntityQueryWrapper.eq("has_delete",0);
		//查出来所有的数据
		List<SysRoleBusinessEntity> sysRoleBusinessEntityList = sysRoleBusinessMapper.selectList(sysRoleBusinessEntityQueryWrapper);
		//找到根节点
		for (SysRoleBusinessEntity sysRoleBusinessEntity : sysRoleBusinessEntityList) {
			if ("0".equals(sysRoleBusinessEntity.getPid())) {
				SysRoleBusinessDTO sysRoleBusinessV3DTO = new SysRoleBusinessDTO();
				sysRoleBusinessV3DTO.setId(sysRoleBusinessEntity.getId());
				sysRoleBusinessV3DTO.setName(sysRoleBusinessEntity.getName());
				sysRoleBusinessV3DTO.setCode(sysRoleBusinessEntity.getCode());
				sysRoleBusinessV3DTO.setHasGroup(sysRoleBusinessEntity.getHasGroup());
				rootTreeLists.add(sysRoleBusinessV3DTO);
			}
		}
		//给根节封装子节点
		List<SysRoleBusinessDTO> ChilTree;
		for (SysRoleBusinessDTO menuNode : rootTreeLists) {
			ChilTree = getChilTree(menuNode.getId(), sysRoleBusinessEntityList);
			menuNode.setChildren(ChilTree);
		}
		return rootTreeLists;
	}
	//递归，建立子树形结构
	private List<SysRoleBusinessDTO> getChilTree(String id, List<SysRoleBusinessEntity> sysRoleBusinessEntityList) {
		List<SysRoleBusinessDTO> chilMenus = new ArrayList<>();

		for (SysRoleBusinessEntity sysRoleBusinessEntity : sysRoleBusinessEntityList) {
			if (id.equals(sysRoleBusinessEntity.getPid())) {
				SysRoleBusinessDTO sysRoleBusinessDTO = new SysRoleBusinessDTO();
				sysRoleBusinessDTO.setId(sysRoleBusinessEntity.getId());
				sysRoleBusinessDTO.setName(sysRoleBusinessEntity.getName());
				sysRoleBusinessDTO.setHasGroup(sysRoleBusinessEntity.getHasGroup());
				sysRoleBusinessDTO.setCode(sysRoleBusinessEntity.getCode());
				chilMenus.add(sysRoleBusinessDTO);
			}
		}
		for (SysRoleBusinessDTO bussiness : chilMenus) {
			bussiness.setChildren(getChilTree(bussiness.getId(), sysRoleBusinessEntityList));
		}
		return chilMenus;
	}
	/**
	 * 获取所有的部门
	 *
	 * @return
	 */
	@Override
	public List<SysDeptDTO> getSysDeptBusiness(String pid) {
		List<SysDeptDTO> rootTreeLists = new ArrayList<>();

		//查出来所有的数据
		List<SysDeptDTO> sysDeptBusinessEntityList = sysRoleBusinessMapper.selectDeptList(pid);
		//找到根节点
		for (SysDeptDTO sysDeptDTO : sysDeptBusinessEntityList) {


		}
		// for(ForPropertyDeptDTO  sysDeptDTO : sysDeptBusinessEntityList) {
		// 	if("0".equals(sysDeptDTO.getPid())) {
		// 		rootTreeLists.add(sysDeptDTO);
		// 	}
		// }
		// //给根节封装子节点
		// List<ForPropertyDeptDTO> ChilTree;
		// for(ForPropertyDeptDTO menuNode : rootTreeLists) {
		// 	ChilTree = getDeptChilTree(menuNode.getId(),sysDeptBusinessEntityList);
		// 	menuNode.setChildren(ChilTree);
		// }
		return sysDeptBusinessEntityList;
	}

	//递归，建立子树形结构
	private List<SysDeptDTO> getDeptChilTree(String id, List<SysDeptDTO> sysRoleBusinessEntityList) {
		List<SysDeptDTO> chilMenus = new ArrayList<>();

		for (SysDeptDTO sysDeptBusinessEntity : sysRoleBusinessEntityList) {
			if (id.equals(sysDeptBusinessEntity.getPid())) {
				chilMenus.add(sysDeptBusinessEntity);
			}
		}
		for (SysDeptDTO bussiness : chilMenus) {
			bussiness.setChildren(getDeptChilTree(bussiness.getId(), sysRoleBusinessEntityList));
		}
		return chilMenus;
	}

	/**
	 * 通过审批角色id和部门id查询审批人
	 *
	 * @param roleBusinessId 审批角色id
	 * @param deptId         部门id
	 * @return
	 */
	@Override
	public List<SysUserRoleBusinessDTO> getUserByRoleAndDept(String roleBusinessId, String deptId) {
		return sysRoleBusinessMapper.getUserByRoleAndDept(roleBusinessId, deptId);
	}

	/**
	 * 通过关键字进行模糊查询
	 *
	 * @param queryKey 关键字查询
	 * @return
	 */
	@Override
	public List<SysDeptDTO> getUserByQueryKey(String queryKey) {
		return sysRoleBusinessMapper.getUserByQueryKey(queryKey);
	}


}